package sjtu.ist.warehouse4ws.action;


import java.io.InputStream;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;

import sjtu.ist.warehouse4ws.jcr.RepositoryMoudl;
import sjtu.ist.warehouse4ws.tool.GenerateWadl;
import sjtu.ist.warehouse4ws.tool.MyUtils;


import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;


public class GenerateWadlAction extends ActionSupport {

	private static final long serialVersionUID = 4532462611069475714L;
	private GenerateWadl generateWadl;
    private RepositoryMoudl repositoryMoudlService;
    
	
	public RepositoryMoudl getRepositoryMoudlService() {
		return repositoryMoudlService;
	}

	public void setRepositoryMoudlService(RepositoryMoudl repositoryMoudlService) {
		this.repositoryMoudlService = repositoryMoudlService;
	}

	String warnning;

	public String getWarnning() {
		return warnning;
	}

	public void setWarnning(String warnning) {
		this.warnning = warnning;
	}

	public void setGenerateWadl(GenerateWadl generateWadl) {
		this.generateWadl = generateWadl;
	}

	public String genarateWadl() throws Exception {
		MyUtils.mkDirectory(ServletActionContext.getServletContext().getRealPath("/upload/files/wadl"));
		
		String outpath=ServletActionContext.getServletContext().getRealPath("/upload/files/wadl/").replaceAll("\\\\", "/")+"/";
		Subject currentUser = SecurityUtils.getSubject();
		String companyId=currentUser.getSession().getAttribute("companyId").toString();	

		HttpServletRequest request = ServletActionContext.getRequest();
		String xmlName = request.getParameter("nodeName");
		String xmlVersion=request.getParameter("nodeVersion");
	   
	  
		List<String> addFile=new ArrayList<String>();
	    HashMap <String,String>fs=this.repositoryMoudlService.getAllFile(companyId, xmlName, xmlVersion,"domain");
		generateWadl.setFs(fs);
	    Iterator it = fs.keySet().iterator();
		while (it.hasNext()) {
			
			String key = (String) it.next();
			String outFile= outpath+"WADL_"+key;
		    if(currentUser.isPermitted("model:towadl")){
					if (generateWadl.writeWadl(outFile, key).equals("缺少关联文件")) warnning="缺少关联文件";
					else addFile.add(outFile);
				}else{
					warnning="无权限操作！";
				}
				
			
			
	
				
		}

		
		
		this.repositoryMoudlService.addServiceFile(companyId, xmlName, xmlVersion, "wadl", addFile);
		return SUCCESS;
	}
}
